package com.giga.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;

@Controller
public class KaptchaController {
    @Autowired
    private DefaultKaptcha captchaProducer;

    /**
     * 登录验证码SessionKey
     */
    public static final String VALIDATE_CODE = "verifyCode";

    /**
     * 前端通过src中/kaptcha获取验证码图片,并保存session
     */
    @RequestMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            var challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 检查验证码是否正确
     */
    @RequestMapping("/checkValidateCode")
    @ResponseBody
    public int checkValidateCode(HttpServletRequest request, @RequestParam("validateCode") String validateCode) {
        int i;
        String loginValidateCode = request.getSession().getAttribute(VALIDATE_CODE).toString();
        if (loginValidateCode == null) {    //验证码过期
            i = 0;
        } else if (loginValidateCode.equals(validateCode)) {    //验证码正确
            i = 1;
        } else {        //验证码不正确
            i = 0;
        }
        return i;
    }
}
